import asyncio
import logging
import signal
import sys

from arkitect.telemetry.logger import INFO
from arkitect.utils.event_loop import get_event_loop
from http_server import start_http_server

# Configure logging
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)

# 全局变量用于存储服务器实例
http_server_task = None

async def shutdown_server():
    """
    优雅关闭服务器的函数
    """
    INFO("正在关闭服务器...")
    
    # 取消HTTP服务器任务
    if http_server_task:
        INFO("正在关闭HTTP服务器...")
        http_server_task.cancel()
        try:
            await http_server_task
        except asyncio.CancelledError:
            pass
    
    INFO("服务器已成功关闭")

async def main():
    """
    Main function to start the HTTP server.
    """
    global http_server_task
    
    # 创建停止事件
    stop = asyncio.Event()
    
    # 定义信号处理函数
    def signal_handler():
        INFO("接收到终止信号，准备关闭服务器...")
        stop.set()

    # 注册信号处理
    loop = asyncio.get_running_loop()
    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, signal_handler)
    
    try:
        # 创建HTTP服务器任务
        http_server_task = asyncio.create_task(start_http_server())
        INFO("HTTP server is starting on http://0.0.0.0:8080")
        
        # 等待停止信号
        await stop.wait()
        
    except Exception as e:
        INFO(f"服务器启动错误: {e}")
        sys.exit(1)
    finally:
        # 优雅关闭服务器
        await shutdown_server()
        sys.exit(0)

if __name__ == "__main__":
    get_event_loop(main())
